use crate::alloc::boxed::Box;
use crate::alloc::collections::LinkedList;
use crate::current_th::CurrentThType;
use crate::scheduler::rt_schedule;
use crate::thread::ObjThread;
use crate::timer::ObjTimer;
use cortex_m_rt::exception;
use rtt_kernel_mutex::KMutex;

// 支持的优先级别
pub const MAX_PRIORITY: usize = 8;

pub static SCHEDULE_FLAG: KMutex<bool> = KMutex::new(true);

// 当前的线程ID号
pub static CURRENT_THREAD: KMutex<CurrentThType> = KMutex::new(CurrentThType::Null);

// 存储等待线程的链表
const VOID_LIST: LinkedList<Box<ObjThread>> = LinkedList::new();
pub static SCHEDULE_LIST: KMutex<[LinkedList<Box<ObjThread>>; MAX_PRIORITY]> =
    KMutex::new([VOID_LIST; MAX_PRIORITY]);

pub static THREAD_DELETE_LIST: KMutex<LinkedList<Box<ObjThread>>> = KMutex::new(LinkedList::new());

pub static TIMER_LIST: KMutex<LinkedList<Box<ObjTimer>>> = KMutex::new(LinkedList::new());

#[exception]
unsafe fn SysTick() {
    SysTick_Handler()
}

fn SysTick_Handler() {
    {
        let mut list = TIMER_LIST.lock();
        // 过滤链表中计时到0的元素
        let zero = list
            .drain_filter(|x| if x.tick() == 0 { true } else { false })
            .collect::<LinkedList<_>>();
        // 删除已经结束的定时器
        for i in zero {
            i.run();
        }
    }

    rt_schedule()
}
